package com.marketlive.app.b2c;

import com.marketlive.app.b2c.struts.formatter.PhoneNumberFormatter;
import com.sourcebeat.strutslive.common.PojoActionForm;
import com.sourcebeat.strutslive.formatter.FormatException;
import com.sourcebeat.strutslive.formatter.Formatter;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;

public class AbstractActionForm extends PojoActionForm
{
  private static Log log = LogFactory.getLog(AbstractActionForm.class);
  private static final long serialVersionUID = 8509307516571608272L;
  private String action = null;

  private ActionErrors errors = new ActionErrors();

  private PhoneNumberFormatter phoneFormatter = new PhoneNumberFormatter();

  public String getAction() {
    return this.action;
  }

  public void setAction(String action) {
    this.action = action;
  }

  public void reset(ActionMapping mapping, HttpServletRequest request)
  {
    super.reset(mapping, request);
  }

  public Object formatValue(Object value, String keypath, Class type)
  {
    if (((value instanceof List)) || ((value instanceof Set)) || (isPhoneFormat(keypath))) {
      return value;
    }

    return super.formatValue(value, keypath, type);
  }

  protected Object convertValue(String keypath, Class type, Object value)
  {
    if (isPhoneFormat(keypath)) {
      Object convertedValue = null;
      try {
        convertedValue = this.phoneFormatter.convertFromPresentationFormat(PhoneNumberFormatter.unwrapString(value));
      }
      catch (FormatException e) {
        cacheUnconvertedValue(keypath, value);
        String retVal = Formatter.unwrapString(value);
        retVal = retVal.replaceAll("[^0-9]", "");
        return retVal;
      }
      return convertedValue;
    }

    return super.convertValue(keypath, type, value);
  }

  protected boolean isPhoneFormat(String keypath) {
    return (keypath.equalsIgnoreCase("billContact.phone1")) || (keypath.equalsIgnoreCase("billContact.phone2")) || (keypath.equalsIgnoreCase("currentContact.phone1")) || (keypath.equalsIgnoreCase("currentContact.phone2")) || (keypath.equalsIgnoreCase("billContact.fax")) || (keypath.equalsIgnoreCase("currentContact.fax"));
  }
}